import { account } from '../config/appwrite';
import { ID } from 'appwrite';

/**
 * Send OTP verification code to email
 * This creates a magic URL session token
 */
export const sendOTPToEmail = async (email: string): Promise<{ userId: string; secret: string }> => {
  try {
    // Create a magic URL session (this sends an OTP email)
    const token = await account.createMagicURLToken(
      ID.unique(),
      email
    );
    
    return {
      userId: token.userId,
      secret: token.secret
    };
  } catch (error: any) {
    console.error('Error sending OTP:', error);
    throw new Error(error.message || 'Failed to send OTP');
  }
};

/**
 * Verify OTP code
 * This completes the magic URL session with the secret code
 */
export const verifyOTP = async (userId: string, secret: string): Promise<boolean> => {
  try {
    // Update the magic URL session with the secret
    await account.updateMagicURLSession(userId, secret);
    return true;
  } catch (error: any) {
    console.error('Error verifying OTP:', error);
    throw new Error(error.message || 'Failed to verify OTP');
  }
};

/**
 * Create email/password account after OTP verification
 */
export const createEmailPasswordAccount = async (
  email: string,
  password: string,
  name: string
): Promise<any> => {
  try {
    const user = await account.create(
      ID.unique(),
      email,
      password,
      name
    );
    return user;
  } catch (error: any) {
    console.error('Error creating account:', error);
    throw new Error(error.message || 'Failed to create account');
  }
};

/**
 * Get current session
 */
export const getCurrentSession = async () => {
  try {
    return await account.get();
  } catch {
    return null;
  }
};

/**
 * Logout current session
 */
export const logout = async () => {
  try {
    await account.deleteSession('current');
  } catch (error: any) {
    console.error('Error logging out:', error);
    throw new Error(error.message || 'Failed to logout');
  }
};
